from django.contrib import admin
from interview.models import Candidate
from django.http import HttpResponse
from interview import candidate_fieldsets as cf
from django.db.models import Q
from interview import dingtalk
from django.contrib import messages

from jobs.models import Resume
from django.utils.safestring import mark_safe

from datetime import datetime
import csv
import logging

logger = logging.getLogger(__name__)

exportable_fields = ('username','city',"phone",'bachelor_school','degree','first_result','first_interviewer_user',
                    'second_result','second_interviewer_user','hr_score','hr_result')

# 通知一面面试官面试
@admin.action(permissions=["notify1"])
def notify_interviewer1(modeladmin, request, queryset):
    candidates = ""
    interviewers = ""
    for obj in queryset:
        candidates = obj.username + ";" + candidates
        if obj.first_interviewer_user is None:
            messages.error(request, '请为'+obj.username+'添加一面面试官')
            return
        interviewers = obj.first_interviewer_user.username + ";" + interviewers
    # 这里的消息发送到钉钉， 或者通过 Celery 异步发送到钉钉
    dingtalk.send("\n候选人 %s \n进入一面面试环节，亲爱的一面面试官 %s \n请准备好面试 " % (candidates, interviewers))
    #send_dingtalk_message.delay("候选人 %s 进入面试环节，亲爱的面试官，请准备好面试： %s" % (candidates, interviewers) )
    messages.add_message(request, messages.INFO, '已经成功发送面试通知')

#国际化文本
notify_interviewer1.short_description = '通知一面面试官'
#有export权限才能导出
#notify_interviewer1.allowed_permissons = ('notify_interviewer1',)

# 通知二面面试官面试
@admin.action(permissions=["notify2"])
def notify_interviewer2(modeladmin, request, queryset):
    candidates = ""
    interviewers = ""
    for obj in queryset:
        candidates = obj.username + ";" + candidates
        if obj.second_interviewer_user is None:
            messages.error(request, '请为'+obj.username+'添加二面面试官')
            return
        interviewers = obj.second_interviewer_user.username + ";" + interviewers
    # 这里的消息发送到钉钉， 或者通过 Celery 异步发送到钉钉
    dingtalk.send("\n候选人 %s \n进入二面面试环节，亲爱的二面面试官 %s \n请准备好面试 " % (candidates, interviewers))
    #send_dingtalk_message.delay("候选人 %s 进入面试环节，亲爱的面试官，请准备好面试： %s" % (candidates, interviewers) )
    messages.add_message(request, messages.INFO, '已经成功发送面试通知')

#国际化文本
notify_interviewer2.short_description = '通知二面面试官'
#有export权限才能导出
#notify_interviewer2.allowed_permissons = ('notify_interviewer2',)

@admin.action(permissions=["export"])
def export_model_as_csv(modeladmin,request,queryset):
    response = HttpResponse(content_type='text/csv')
    field_list = exportable_fields
    #可以使用 request 中的 User-Agent 进行客户端系统判断，如果用户的系统是 Windows，那么给导出的文件编码设置为带有 BOM 的 UTF-8，否则使用 UTF-8
    response.charset = 'utf-8-sig' if "Windows" in request.headers.get('User-Agent') else 'utf-8'
    #Content-Disposition 响应标头指示回复的内容该以何种形式展示，是以内联的形式（即网页或者页面的一部分），还是以附件的形式下载并保存到本地
    response['Context-Disposition'] = 'attachment; filename=%s-list-%s.csv' % (
        'recruitment-candidates',
        datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
    )

    # 写入表头
    # print(response['Context-Disposition'])
    writer = csv.writer(response)
    writer.writerow(
        [queryset.model._meta.get_field(f).verbose_name.title() for f in field_list]
    )

    for obj in queryset:
        # 单行的记录(各个字段的值)，写入csv文件
        csv_line_values = []
        for field in field_list:
            field_object = queryset.model._meta.get_field(field)
            field_value = field_object.value_from_object(obj)
            csv_line_values.append(field_value)
        writer.writerow(csv_line_values)

    logger.info("%s exported %s candidate records" % (request.user,len(queryset)))

    return response

#国际化文本
export_model_as_csv.short_description = '导出为CSV文件'
#有export权限才能导出
#export_model_as_csv.allowed_permissons = ('export',)

class CandidateAdmin(admin.ModelAdmin):
    actions = [export_model_as_csv,notify_interviewer1,notify_interviewer2]
    ### 当前用户是否有导出权限
    def has_export_permission(self,request):
        opts = self.opts
        return request.user.has_perm('%s.%s' % (opts.app_label, "export"))
    ### 当前用户是否有发送通知权限
    def has_notify1_permission(self,request):
        opts = self.opts
        return request.user.has_perm('%s.%s' % (opts.app_label, "notify1"))

        ### 当前用户是否有发送通知权限
    def has_notify2_permission(self, request):
        opts = self.opts
        return request.user.has_perm('%s.%s' % (opts.app_label, "notify2"))

    exclude = ('creator','created_date','modified_date')
    list_display = ('username','city','get_resume','bachelor_school','first_score','first_result','first_interviewer_user',
                    'second_result','second_interviewer_user','hr_score','hr_result','last_editor')

    # 筛选条件
    list_filter = ('city','first_result','second_result','hr_result',
                   'first_interviewer_user','second_interviewer_user','hr_interviewer_user')

    # 查询字段
    search_fields = ('username','phone','email','bachelor_school')

    # 自动排序字段
    ordering = ('hr_result','second_result','first_result')

    # 获取简历
    def get_resume(self, obj):
        if not obj.phone:
            return ""
        # 按手机号过滤出简历
        resumes = Resume.objects.filter(phone=obj.phone)
        # 当简历存在时
        if resumes and len(resumes) > 0:
            return mark_safe(u'<a href="/resume/%s" target="_blank">%s</a' % (resumes[0].id, "查看简历"))
        return ""

    get_resume.short_description = '查看简历'
    # 允许HTML标签
    get_resume.allow_tags = True


    # 设置面试官只读字段
    ###readonly_fields = ('first_interviewer_user','second_interviewer_user')
    def get_group_names(self,user):
        group_names = []
        for g in user.groups.all():
            group_names.append(g.name)
        return group_names

    # 对于非管理员，非HR，获取自己是一面面试官或者二面面试官的候选人集合：
    def get_queryset(self, request):  # show data only owned by the user
        qs = super(CandidateAdmin, self).get_queryset(request)
        group_names = self.get_group_names(request.user)
        if request.user.is_superuser or 'hr' in group_names:
            return qs
        return Candidate.objects.filter(
            Q(first_interviewer_user = request.user) | Q(second_interviewer_user = request.user))

    def get_readonly_fields(self, request, obj):
        group_names = self.get_group_names(request.user)
        if 'interviewer' in group_names:
            logger.info("interviewer is in user's group for %s" % request.user.username)
            return ('first_interviewer_user', 'second_interviewer_user')
        return ()

    # 设置只有管理员和hr可以直接编辑字段
    default_list_editable = ('first_interviewer_user','second_interviewer_user')

    def get_list_editable(self, request):
        group_names = self.get_group_names(request.user)
        if request.user.is_superuser or 'hr' in group_names:
            return self.default_list_editable
        return ()

    def get_changelist_instance(self, request):
        self.list_editable = self.get_list_editable(request)
        return super(CandidateAdmin,self).get_changelist_instance(request)

    # 一面面试官仅填写一面反馈，二面面试官可以填写二面反馈
    def get_fieldsets(self, request, obj=None):
        group_names = self.get_group_names(request.user)
        if 'interviewer' in group_names and obj.first_interviewer_user == request.user:
            return cf.default_fieldsets_first
        if 'interviewer' in group_names and obj.second_interviewer_user == request.user:
            return cf.default_fieldsets_second
        return cf.default_fieldsets

    def save_model(self, request, obj, form, change):
        obj.last_editor = request.user.username
        if not obj.creator:
            obj.creator = request.user.username
        obj.modified_date = datetime.now()
        obj.save()

admin.site.register(Candidate,CandidateAdmin)